<template>
    <view class="page-order bg-content">
        <u-sticky>
            <div style="height: 84px; border-bottom: 1rpx solid #eeeeee; background-color: #FFFFFF;">
                <u-search placeholder="商品名称/订单号/支付流水号" v-model="searchKeyword" @search="onSearch" @custom="onSearch"></u-search>
                <u-tabs :list="tabList" name="title" :gutter="20" active-color="red" :current="activeTabIndex" @change="onTabChange"></u-tabs>
            </div>
        </u-sticky>

        <view class="order" v-for="(tbOrder, index) in tbOrderList" :key="tbOrder.id">
            <view class="top">
                <view class="left" @click="navigateTo('/pages/common/store/index', {storeId: tbOrder.tbStore.id})">
                    <u-icon name="/pages/sub/sub1-tabs/static/icon/shop.png" :size="40" color="rgb(94,94,94)"></u-icon>
                    <view class="store">{{ tbOrder.tbStore.name }}</view>
                    <u-icon name="arrow-right" color="rgb(203,203,203)" :size="26"></u-icon>
                </view>
                <view class="right">{{ tbOrder.statusText }}</view>
            </view>
            <view class="item" v-for="(tbOrderGoods, i) in tbOrder.tbOrderGoodsList" :key="tbOrderGoods.id" @click="gotoOrderDetail(tbOrder)">
                <view class="left">
                    <image :src="tbOrderGoods.image ? tbOrderGoods.image + '?imageView2/1/w/300/h/300' : '/pages/sub/sub1-tabs/static/default-image/goods.jpg'"
                           mode="aspectFill"></image>
                </view>
                <view class="content">
                    <view class="title u-line-2">{{ tbOrderGoods.title }}</view>
                    <view class="type">
                        {{tbOrderGoods.specName}}<label v-if="tbOrderGoods.colorId">;{{tbOrderGoods.colorName}}</label>
                    </view>
                </view>
                <view class="right">
                    <view class="price">
                        ￥{{ tbOrderGoods.price | toFixed2 }}
                    </view>
                    <view class="number">x{{ tbOrderGoods.quantity }}</view>
                </view>
            </view>
            <view class="total">
                共{{ tbOrder.quantity }}件商品 实付:
                <text class="total-price">
                    ￥{{ tbOrder.payMoney | toFixed2 }}
                </text>
            </view>
            <view class="bottom" v-if="tbOrder.enableOperation">
                <div class="order-btn-group" style="width: 100%; text-align: right;">
                    <u-button plain size="mini" v-if="tbOrder.status === '0'"
                                @click="updateStatus(tbOrder, '6', '是否确认取消订单？')">取消订单
                    </u-button>

                    <u-button plain type="error" size="mini" v-if="tbOrder.status === '0'"
                                @click="immediatelyPay(tbOrder)">立即支付
                    </u-button>

                    <!--直接退款-->
                    <u-button plain size="mini" v-if="tbOrder.status === '1' && tbOrder.tbStore.isSupportRefund"
                                @click="applyRefund(tbOrder)">
                        申请退款
                    </u-button>

                    <u-button plain size="mini" v-if="'1,2'.indexOf(tbOrder.status) != -1"
                                @click="updateStatus(tbOrder, '3', '是否确认收货？')">
                        确认收货
                    </u-button>

                    <u-button plain size="mini" v-if="'3,4'.indexOf(tbOrder.status) != -1 && !tbOrder.isComment"
                                @click="gotoOrderGoodsComment(tbOrder)">
                        评价
                    </u-button>
                </div>
            </view>
        </view>

        <view class="centre" v-if="!tbOrderList.length">
            <image src="/pages/sub/sub1-tabs/static/img/taobao-order.png" mode=""></image>
            <view class="explain">
                您还没有相关的订单
                <view class="tips">可以去看看有那些想买的</view>
            </view>
            <view class="btn" @click="uni.reLaunch({url: '/pages/sub/sub1-tabs/tabs/index'})">随便逛逛</view>
        </view>

        <div style="padding-top: 10px; padding-bottom: 10px;" v-if="tbOrderList.length">
            <u-loadmore :status="pagination.status" bg-color="#eeeeee"/>
        </div>

        <immediatelyPay ref="immediatelyPayRef"></immediatelyPay>
    </view>
</template>

<script>

    import immediatelyPay from '@/components/immediately-pay.vue'
    import {CommonUtil} from "@/dev/core/utils/common.util";
    import {TbOrderService} from "@/dev/services/tb-order.service";

    export default {
        data() {
            return {
                tbOrderList: [],
                searchKeyword: '',
                tabList: [
                    {title: '全部', saleMode: '0'},
                    {title: '待付款', saleMode: '0', status: '0'},
                    {title: '待发货', saleMode: '0', status: '1'},
                    {title: '待收货', saleMode: '0', status: '2'},
                    {title: '已取消', saleMode: '0', status: '6'},
                    {title: '待评价', saleMode: '0', status: '4', isComment: 0},
                ],
                activeTabIndex: -1,
            }
        },
        components: {
            immediatelyPay,
        },
        onShow() {
            const _self = this;
            this.activeTabIndex = parseInt(this.urlParams.activeTabIndex)
            this.$forceUpdate();
        },
        watch: {
            activeTabIndex: {
                deep: true, // 深度监听
                handler(newVal, oldVal) {
                    console.log("activeTabIndex参数改变，即将刷新...", `新值：${newVal}`, `旧值：${oldVal}`)
                    this.doRefresh(this.tbOrderList)
                }
            }
        },
        // 上拉加载
        onReachBottom: function () {
            if (this.pagination.hasNextPage) {
                this.doInfinite()
            }
        },
        methods: {
            onSearch() {
                const _self = this;
                this.searchKeyword = CommonUtil.trim(this.searchKeyword)
                _self.doRefresh(_self.tbOrderList)
            },
            onTabChange(index) {
                const _self = this;
                this.activeTabIndex = index;
                this.urlParams.activeTabIndex = this.activeTabIndex;
            },
            /**
             * 加载更多数据中
             * @param infiniteScroll
             */
            doInfinite(infiniteScroll) {
                const _self = this;
                new TbOrderService().findTableListCascade({
                    pagination: this.pagination,
                    data: {
                        communityId: this.globalVariable.userInfo.tbCommunity.id,
                        userId: this.globalVariable.userInfo.id,
                        saleMode: this.tabList[this.activeTabIndex].saleMode,
                        status: this.tabList[this.activeTabIndex].status,
                        isComment: this.tabList[this.activeTabIndex].isComment,
                        orderBy: 'create_time desc',
                        searchKeyword: this.searchKeyword
                    }
                }).then(result => {
                    console.log(_self.tbOrderList)
                    _self.pagination.refreshPage(result)
                    _self.tbOrderList = [..._self.tbOrderList, ...result.list]
                })
            },
            applyRefund(tbOrder) {
                let itemList = [
                    "多拍、拍错、不想要",
                    "打算重拍",
                    "其他"
                ];
                uni.showActionSheet({
                    itemList: itemList,
                    success: function (res) {
                        console.log(res);
                        console.log('选中了第' + (res.tapIndex + 1) + '个按钮');
                        console.log(itemList[res.tapIndex]);
                        new TbOrderService().updateStatus({
                            id: tbOrder.id,
                            status: "5",
                            refundReason: itemList[res.tapIndex]
                        }).then(result => {
                            if (result.status === 'success') {
                                Object.assign(tbOrder, CommonUtil.deleteNullAttrInObject(result.data))
                            }
                            CommonUtil.alert(result.message);
                        });
                    },
                    fail: function (res) {
                        console.log(res.errMsg);
                    }
                });
            },
            updateStatus(tbOrder, status, hint) {
                const _self = this;
                CommonUtil.alert({
                    title: '提示！',
                    content: hint,
                    showCancel: true, // 是否显示取消按钮
                    success: function (res) {
                        if (res.cancel) { // 点击取消,默认隐藏弹框
                        } else { // 点击确定
                            new TbOrderService().updateStatus({
                                id: tbOrder.id,
                                status: status,
                            }).then(result => {
                                if (result.status === 'success') {
                                    Object.assign(tbOrder, CommonUtil.deleteNullAttrInObject(result.data))
                                    CommonUtil.alert('操作成功');
                                } else {
                                    CommonUtil.alert(result.message);
                                }
                            });
                        }
                    }
                });
            },
            gotoOrderDetail(tbOrder) {
                this.navigateTo(`/pages/sub/sub1-tabs/tabs/person/order/order-detail/index`, null, tbOrder);
            },
            gotoOrderGoodsComment(tbOrder){
                this.navigateTo('/pages/sub/sub1-tabs/tabs/person/order/order-goods-comment/index', null, tbOrder);
            },
            immediatelyPay(tbOrder) {
                const _self = this;
                this.$refs.immediatelyPayRef.pay({
                    tbOrder: tbOrder,
                    callback: function (tbOrder, payResult) {
                        console.log("tbOrder", payResult);
                        if (payResult) {
                            _self.tbOrderList = [];
                            _self.$nextTick(() => {
                                _self.doRefresh(_self.tbOrderList)
                            });
                        }
                    }
                });
            },
        }
    }
</script>

<style lang="scss" scoped>
    @import "./index.scss";
</style>

<style lang="scss">
    .page-order {
        .order-btn-group{
            button {
                margin-left: 10px;
            }
        }
    }
</style>
